﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Yunlib.Common
{
    public class CheckSumHelper
    {
        /// <summary>
        /// {DomainName};{PluginId};{PluginName};{UserName};{InternalBookmark};{Osql}
        /// </summary>
        private const string ChecksumFormat = "{0};{1};{2};{3}";

        /// <summary>
        /// validate checksum string
        /// </summary>
        /// <param name="pluginId"></param>
        /// <param name="pluginName"></param>
        /// <param name="userName"></param>
        /// <param name="checksum"></param>
        /// <returns></returns>
        public static bool IsValid(string checksum, string appkey, string action, string paras, string timestamp)
        {
            string realChecksum = GenCheckSum(appkey, action, paras, timestamp);

            return realChecksum.Equals(checksum);
        }


        /// <summary>
        /// Generate checksum string
        /// </summary>
        /// <param name="pluginId"></param>
        /// <param name="pluginName"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static string GenCheckSum(string appkey, string action, string paras, string timestamp)
        {
            string strCheckSum = string.Format(ChecksumFormat, appkey, action, paras, timestamp);
            strCheckSum = Encrypt(strCheckSum);
            return strCheckSum;
        }

        /// <summary>
        /// Encrypt checksum string
        /// </summary>
        /// <param name="plainText"></param>
        /// <returns></returns>
        static string Encrypt(string plainText)
        {
            // instant md5 object
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();

            // convert string to byte array
            byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(plainText));

            // build encrypted text
            StringBuilder strBuilder = new StringBuilder();

            // re-format each byte in data as hexadecimal string
            for (int index = 0; index < data.Length; index++)
                strBuilder.Append(data[index].ToString("x2"));

            // clear md5 instant
            md5.Clear();

            return strBuilder.ToString();
        }

    }
}
